package com.lvhx.springboot.base;

import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.util.Assert;

public class SpringTransactionManager implements TransactionManager<TransactionStatus> {
	private PlatformTransactionManager transactionManager;
	private TransactionDefinition transactionDefinition;

	public SpringTransactionManager(
			PlatformTransactionManager transactionManager,
			TransactionDefinition transactionDefinition) {
		Assert.notNull(transactionManager, "transactionManager may not be null");
		this.transactionManager = transactionManager;
		this.transactionDefinition = transactionDefinition;
	}
	
    public SpringTransactionManager(PlatformTransactionManager transactionManager) {
        this(transactionManager, new DefaultTransactionDefinition());
    }
    
    public SpringTransactionManager() {
        this.transactionDefinition = new DefaultTransactionDefinition();
    }
    
    @Override
    public TransactionStatus startTransaction() {
        return transactionManager.getTransaction(transactionDefinition);
    }
    
    @Override
    public void commitTransaction(TransactionStatus tx) {
//        if (tx.isNewTransaction() && !tx.isCompleted()) {
            transactionManager.commit(tx);
//        }
    }
    
    @Override
    public void rollbackTransaction(TransactionStatus tx) {
        if (tx.isNewTransaction() && !tx.isCompleted()) {
            transactionManager.rollback(tx);
        }
    }
    
    public void setTransactionManager(PlatformTransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }
    
    public void setTransactionDefinition(TransactionDefinition transactionDefinition) {
        this.transactionDefinition = transactionDefinition;
    }
}
